<template>
  <div class="signUp">
    <ListTab
      v-model="tabStatus"
      :show-header="!showMobilePage"
      :tabs="tabs"
      :max-badge="{ num: 100, str: '99+' }"
      is-table
      @tabClick="handleTabClick"
    />
    <div :class="{'mobile-table mobile-min-height':showMobilePage}" class="min-fill-page signUp-list">
      <div v-if="!showMobilePage" class="filter">
        <FilterInput
          ref="FilterToolRef"
          v-model="paramsObj"
          :filter-list="filterList"
          show-search-btn
          @handelClick="queryClick"
          @queryEmpty="queryEmpty"
          @filterTagStatus="filterTagStatus"
        />
        <createBtn
          v-if="hasRouteAuth('crm:original:create')"
          style="margin-right: 10px;"
          @click.native="toCreate"
        />
        <MoreOpeator
          ref="btnGroupRef"
          :list="[
            { label: '批量抄送', handelClick: handleSendMsg },
            { label: '复制链接', handelClick: batchCopyLink }
          ]"
        />
      </div>
      <div class="table-list">
        <div v-loading="listLoading" style="min-height: 300px">
          <u-table
            v-if="list.items.length"
            ref="tableRef"
            :data="list.items"
            :height="setTableHeight"
            :row-height="rowHeight()"
            :border="true"
            beautify-table
            header-drag-style
            use-virtual
            class="fb-table"
            element-loading-text="加载中..."
            empty-text="暂无数据"
            header-cell-class-name="order-data-header-cell"
            fit
            hightlight-current-row
            @select="selectTable"
            @select-all="selectTable"
          >
            <u-table-column
              :fixed="selectFixed"
              align="center"
              type="selection"
              width="50"
            />
            <u-table-column :min-width="handleTdWidth()" align="left" label="审批单号" label-class-name="diy-cell" class-name="diy-cell">
              <template slot-scope="scope" slot="header">
                <div class="diyHeader">{{ scope.column.label }}</div>
              </template>
              <template slot-scope="scope">
                <processSn :is-expedited="scope.row.isExpedited">
                  <div
                    v-if="scope.row.sn"
                    style="cursor: pointer; color: #406eff"
                    @click="toDetail(scope.row)"
                  >
                    <ToolTip :content="handleSnNumber(scope.row.sn)" is-can-click @handelClick="toDetail(scope.row)" />
                  </div>
                  <div v-else>--</div>
                </processSn>
              </template>
            </u-table-column>
            <u-table-column align="left" label="项目名称" min-width="110">
              <template slot-scope="scope">
                <el-tooltip placement="top">
                  <el-scrollbar slot="content">
                    <div style="max-width: 200px;max-height: 200px;" v-html="brProjectName(scope.row.contracts)" />
                  </el-scrollbar>
                  <div class="ellipsis">{{ scope.row.projectName || '--' }}</div>
                </el-tooltip>
              </template>
            </u-table-column>
            <u-table-column align="left" label="申请说明">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.applyRemark" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="状态">
              <template slot-scope="scope">
                <el-tooltip
                  v-if="scope.row.status || scope.row.status === 0"
                  :open-delay="800"
                  class="item"
                  placement="top"
                  effect="dark"
                >
                  <div slot="content">
                    {{ scope.row.status | originalStatus }}
                  </div>
                  <div style="display: flex; align-items: center">
                    <div :class="`color-${scope.row.status}`" class="dot" />
                    <div>{{ scope.row.status | originalStatus }}</div>
                  </div>
                </el-tooltip>
                <div v-else>--</div>
              </template>
            </u-table-column>
            <u-table-column align="left" label="当前节点">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.currentNode" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="当前处理人" min-width="110">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.proposer" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="所属部门">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.departmentName" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="创建人">
              <template slot-scope="scope">
                <ToolTip :content="scope.row.createUser" />
              </template>
            </u-table-column>
            <u-table-column align="left" label="创建时间" min-width="160">
              <template slot-scope="scope">
                <ToolTip :content="format(scope.row.createTime, 'YYYY/MM/DD HH:mm:ss')" />
              </template>
            </u-table-column>
            <u-table-column :width="operateWidth" align="left" label="操作" fixed="right">
              <template slot-scope="scope">
                <div class="operate">
                  <el-button v-if="scope.row.status !== 0 && !showMobilePage" type="text" @click="toDetail(scope.row)">
                    <span style="font-size: 14px">查看</span>
                  </el-button>
                  <MoreOpeator
                    :list="[
                      {label: '查看', handelClick: () => {toDetail(scope.row)}, auth: showMobilePage && scope.row.status !== 0},
                      {label: '复制', handelClick: () => {handlerCreateNew(scope.row)}, disabled: scope.row.status === 0 || !hasRouteAuth('crm:original:create')},
                      {label: '编辑', handelClick: () => {toEdit(scope.row)}, disabled: setEditDisable(scope.row)},
                      {label: '删除', handelClick: () => {toDelete(scope.row)}, disabled: setDelDisable(scope.row)},
                    ]"
                  >
                    <div v-if="!showMobilePage" slot="button" :class="{'border-left':scope.row.status !== 0}" class="button-text">更多<i class="el-icon-arrow-down"/></div>
                    <el-image v-else slot="button" :src="operateBtns" class="dropdown-img"/>
                  </MoreOpeator>
                </div>
              </template>
            </u-table-column>
          </u-table>
          <EmptyPlaceholder
            v-else-if="!list.isInit"
            slot="empty"
            empty-text="暂无数据"
            mode="table"
            style="padding-bottom: 0"
          />
          <el-row v-if="showMobilePage" type="flex" justify="left">
            <SelectionNum :select-item="multipleSelectionAll" @clearMixinSelection="clearMixinSelection" />
            <el-pagination
              v-show="list.total > 0"
              :current-page.sync="page"
              :page-size="perPage"
              :total="list.total"
              :small="true"
              :page-sizes="[20, 50, 100, 250, 500]"
              :layout="pageLayout"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-row>
        </div>
        <fixed-pagination v-if="list.total > 0 && !showMobilePage || showMobilePage">
          <template v-if="showMobilePage">
            <FilterInput
              ref="FilterToolRef"
              v-model="paramsObj"
              :filter-list="filterList"
              show-search-btn
              show-mobile-icon
              @handelClick="queryClick"
              @queryEmpty="queryEmpty"
              @filterTagStatus="filterTagStatus"
            />
            <MoreOpeator
              ref="btnGroupRef"
              :list="[
                { label: '批量抄送', handelClick: handleSendMsg },
                { label: '复制链接', handelClick: batchCopyLink }
              ]"
              show-mobile-icon
            />
            <createBtn
              v-if="hasRouteAuth('crm:original:create')"
              mobile-table
              @click.native="toCreate"
            />
          </template>
          <template v-else>
            <SelectionNum :select-item="multipleSelectionAll" @clearMixinSelection="clearMixinSelection" />
            <div style="flex: 1" />
            <el-pagination
              v-show="list.total > 0"
              :current-page.sync="page"
              :page-size="perPage"
              :total="list.total"
              :page-sizes="[20, 50, 100, 250, 500]"
              layout="total, prev, pager, next, sizes, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </template>
        </fixed-pagination>
      </div>
      <DiversAuditorDialog ref="auditorDialog" :can-empty="false" @handleSender="handleBatchSender" />
    </div>
  </div>
</template>
<script>
import createBtn from '@/components/Common/baseComponent/createBtn';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import MoreOpeator from '@/components/Common/baseComponent/moreOpeator';
import DiversAuditorDialog from '@/components/Common/auditProcess/module/diversAuditorDialog';
import ListTab from '@/components/ListTab';
import { energyStatus as originalStatus } from '@/filters/status';
import { expeditedOptions } from '@/filters/status';
import { format } from '@/filters/date';
import { getOriginalTab, getOriginal, deleteOriginal } from '@/api/original';
import { getDepartmentAll } from '@/api/config';
import { paramsRangeFormat } from '@/utils/paramsFormat';
import { hasRouteAuth } from '@/utils/permission';
import ElMessage, { showModal } from '@/utils/message';
import { commonOptions } from '@/utils/tools';
import { PROCESS_TYPE } from '@/utils/const/process';
import filterObjStoreMixin from '@/mixins/filterObjStore';
import TableAdaptive from '@/mixins/tableAdaptive';
import mobileTable from '@/mixins/mobileTable';
import tableSelections from '@/mixins/tableSelections';
import copyLink from '@/mixins/copyLink';
import schedule from '@/mixins/schedule';
import axios from 'axios';
import { mapState } from 'vuex';

export default {
  filters: {
    originalStatus
  },
  components: {
    ListTab,
    EmptyPlaceholder,
    createBtn,
    MoreOpeator,
    DiversAuditorDialog
  },
  mixins: [TableAdaptive, mobileTable, filterObjStoreMixin, tableSelections, copyLink, schedule],
  data() {
    return {
      tabs: [],
      list: {
        items: [],
        total: 0,
        isInit: true
      },
      tabStatus: -1,
      page: 1,
      perPage: 20,
      paramsObj: {},
      listLoading: false,
      deptTreeList: [],
      tableRefName: 'tableRef',
      idKey: 'id',
      isUmyTable: true,
      cancelToken: null,
      rangeKeyArr: [{ attr: 'createTime', start: 'createStartTime', end: 'createEndTime', type: 'time' }]
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    filterList() {
      return [{ keyword: 'sn', name: '审批单号', labelWidth: '100px', type: 'input' },
        { keyword: 'projectName', name: '项目名称', labelWidth: '100px', type: 'input' },
        { keyword: 'applyRemark', name: '申请说明', labelWidth: '100px', type: 'input' },
        { keyword: 'createUser', name: '创建人', labelWidth: '100px', type: 'input' },
        { keyword: 'currentNode', name: '当前节点', labelWidth: '100px', type: 'input' },
        { keyword: 'proposer', name: '当前处理人', labelWidth: '100px', type: 'input' },
        { keyword: 'comment', name: '评论', type: 'input', labelWidth: '100px' },
        { keyword: 'approvalComment', name: '审批意见', type: 'input', labelWidth: '100px' },
        { keyword: 'status', name: '状态', type: 'select', options: commonOptions },
        { keyword: 'departmentId', name: '所属部门', type: 'cascaderSelect', childrenVal: 'children', options: this.deptTreeList },
        { keyword: 'isExpedited', name: '是否加急', type: 'select', options: expeditedOptions },
        { keyword: 'createTime', name: '创建时间', labelWidth: '100px', timeType: 'daterange', type: 'rangeDate' }];
    }
  },
  created() {
    this.queryDeptTreeList();
  },
  beforeRouteEnter(to, from, next) {
    to.meta.isChange = ['originalCreate', 'originalEdit', 'originalDetail'].includes(from.name);
    next();
  },
  activated() {
    if (this.$route.meta.isChange) {
      this.fetchData();
    } else {
      this.fetchData(true);
    }
  },
  methods: {
    hasRouteAuth,
    format,
    getDetailLink(item) {
      if (!item.status) return null;
      return `${location.origin}#/legal/originalDetail?originalId=${item.id}&processId=${item.processId}`;
    },
    brProjectName(name) {
      if (!name || name.length === 0) return '--';
      name = name.join(',\v');
      return name.replace(/\v/g, '<br/>');
    },
    async queryDeptTreeList() {
      const res = await getDepartmentAll();
      this.deptTreeList = (res && res.data) || [];
    },
    async getTabs() {
      const params = this.formatParams();
      delete params.tabStatus;
      const res = await getOriginalTab(params);
      this.tabs = res.data;
    },
    handleTabClick(id) {
      this.tabStatus = id;
      this.list = { items: [] };
      this.fetchData(true);
    },
    fetchData(reset = false) {
      this.listLoading = true;
      if (this.cancelToken) this.cancelToken.cancel('cancel');
      const source = axios.CancelToken.source(); // 用于取消请求
      this.cancelToken = source;
      this.getTabs();
      if (reset) this.page = 1;
      const params = this.formatParams();
      getOriginal(params, source.token).then(res => {
        this.listLoading = false;
        if (res.code !== 200) {
          this.$message.error(res.message);
          return;
        }
        this.list = res.data;
        this.list.isInit = false;
        this.setSelectRow && this.setSelectRow(res.data.items);
      }).catch(err => {
        this.listLoading = false;
        console.log(err);
      });
    },
    formatParams() {
      const params = _.cloneDeep(this.paramsObj);
      paramsRangeFormat(this.rangeKeyArr, params);
      params.page = this.page;
      params.perPage = this.perPage;
      params.tabStatus = this.tabStatus;
      return params;
    },
    setEditDisable(data) {
      return !(data.status === 0 && data.creatorId === this.userInfo.id);
    },
    setDelDisable(data) {
      const statusArr = [0, 2, 3, 5]; // 草稿、已作废、未过审、待提交
      return !(
        statusArr.indexOf(data.status) !== -1 &&
        (data.creatorId === this.userInfo.id || hasRouteAuth('crm:original:delete'))
      ); // 除审批中和已完成状态且 为创建人或有删除权限
    },
    toCreate() {
      this.$router.push({
        name: 'originalCreate'
      });
    },
    toEdit(row) {
      this.$router.push({
        name: 'originalEdit',
        query: {
          originalId: row.id
        }
      });
    },
    toDetail(row) {
      this.filterObjStore(PROCESS_TYPE.ORIGINAL);
      this.$router.push({
        name: 'originalDetail',
        query: {
          originalId: row.id,
          processId: row.processId,
          fromList: 1
        }
      });
    },
    toDelete(row) {
      showModal('是否确定删除?', '', {
        iconClass: 'del-icon'
      }).then(() => {
        deleteOriginal(row.id).then(res => {
          if (res.code === 200) {
            ElMessage.success(res.message);
            if (this.page > 1 && this.perPage * (this.page - 1) + 1 === this.list.total) {
              this.page--;
            }
            this.resetItemSelected(row.id);
            this.fetchData();
          }
        }).catch(err => {
          console.log(err);
        });
        this.fetchData();
      }).catch(() => { return false; });
    },
    queryClick() {
      this.fetchData(true);
    },
    queryEmpty() {
      this.paramsObj = {};
      this.fetchData(true);
    },
    handleSizeChange(val) {
      this.perPage = val;
      this.fetchData();
    },
    handleCurrentChange(page) {
      this.page = page;
      this.fetchData();
    },
    handlerCreateNew(row) { // 再次发起（复制）
      const routeUrl = this.$router.resolve({
        name: 'originalEdit',
        query: {
          createNew: 1,
          originalId: row.id,
          reapplyId: row.processId
        }
      });
      window.open(routeUrl.href, '_blank');
    }
  }
};
</script>
<style lang="scss" scoped>
$bgc: #FFBC3D 0, #FD8546 1, #FF4E5F 2, #999 3, #31CC9C 4, #406EFF 5;
.signUp {
  .signUp-list {
    margin: 16px 16px 0 16px;
    background-color: #fff;
    padding: 20px 24px 55px 24px;
  }
  .operate {
    display: flex;
    align-items: center;
  }
  .border-left {
    position: relative;
    padding-left: 6px;
    margin-left: 6px;
    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      margin-top: -7px;
      width: 1px;
      background: #ddd;
      height: 14px;
    }
  }
  .filter {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
    .create-btn {
      height: 32px;
      font-size: 14px;
      padding: 0 15px;
    }
  }
  .dot {
    width: 4px;
    height: 4px;
    border-radius: 50%;
    margin-right: 5px;
    @each $c, $i in $bgc {
      &.color-#{$i} {
        background: $c;
      }
    }
  }
  .pointer {
    cursor: pointer;
  }
}
</style>
